#include "errors.h"

int keepers_in_action = 0;

static struct sigaction old_action;
static struct sigaction my_action;

static void (*old_signal_handler)(int);

int exception_handler(long val) {
	if(keepers_in_action==0) {// no handlers installed
		return 1;
	} else {
		return 0;
	}
}

void sighandler(int sig)
{
    sigset_t block;
    sigemptyset (&block);
    sigaddset (&block, sig);
    sigprocmask(SIG_UNBLOCK, &block, NULL);
    if(sig==SIGINT) {
        pari_err(talker, "user interrupt"); 
    } else {
        pari_err(talker, "unknown signal"); 
    }        
    return;
}

ExceptionKeeper::ExceptionKeeper() : restored(false) {
	memcpy(&__old_env, &(GP_DATA->env), sizeof(jmp_buf));
    if(keepers_in_action==0) {
        my_action.sa_handler = sighandler;
        sigemptyset(&my_action.sa_mask);
        my_action.sa_flags = SA_RESTART;
        if(sigaction(SIGINT, &my_action, &old_action)!=0) {
            printf("Error\n");
        }
    }
    keepers_in_action++;
}

ExceptionKeeper::~ExceptionKeeper() {
    restore();
}

void ExceptionKeeper::restore() {
	if(!restored) {
		keepers_in_action--;
        if(keepers_in_action==0) {
            if(sigaction(SIGINT, &old_action, NULL)!=0) {
                printf("Error\n");
            }
        }
		memcpy(&(GP_DATA->env), &__old_env, sizeof(jmp_buf));
		restored = true;
	}
}
